package com.qk.common.util.oss;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.qk.common.config.AliYunOSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * OSS
 *
 * @author 上官徵羽
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class AliyunOSSOperators {
    @Autowired
    private AliYunOSSProperties aliYunOSSProperties;

    public String upload(byte[] bytes, String uniqueFileName) throws com.aliyuncs.exceptions.ClientException {
        String newFileName = UUID.randomUUID() + uniqueFileName.substring(uniqueFileName.lastIndexOf("."));
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "qk/user/" + newFileName;

        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = null;
        try {
            ossClient = OSSClientBuilder.create()
                    .endpoint(aliYunOSSProperties.getEndpoint())
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(aliYunOSSProperties.getRegion())
                    .build();
            ossClient.putObject(aliYunOSSProperties.getBucketName(), objectName, new ByteArrayInputStream(bytes));
            return "https://" + aliYunOSSProperties.getBucketName() + "." + aliYunOSSProperties.getEndpoint().split("//")[1] + "/" + objectName;
        } catch (Exception oe) {
            log.error("上传文件失败:{}",oe.getMessage());
            throw oe;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }
}